/**
 * 
 */
package net.mikoo.seals.boss.biz.services.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import net.mikoo.seals.boss.biz.mapper.boss.PartyMapper;
import net.mikoo.seals.boss.biz.mapper.boss.PartyRoleMapper;
import net.mikoo.seals.boss.biz.mapper.boss.PersonMapper;
import net.mikoo.seals.boss.biz.mapper.boss.UserLoginMapper;
import net.mikoo.seals.boss.biz.services.PartyServices;
import net.mikoo.seals.boss.common.BaseServices;
import net.mikoo.seals.boss.common.PageModel;
import net.mikoo.seals.boss.common.WebContext;
import net.mikoo.seals.boss.common.enums.PartyStatusEnum;
import net.mikoo.seals.boss.common.exception.ParametersException;
import net.mikoo.seals.boss.common.utils.IPUtil;
import net.mikoo.seals.boss.common.utils.MD5Util;
import net.mikoo.seals.boss.model.Party;
import net.mikoo.seals.boss.model.PartyQuery;
import net.mikoo.seals.boss.model.PartyRole;
import net.mikoo.seals.boss.model.Person;
import net.mikoo.seals.boss.model.UserLogin;

/**
 * @author huangxm
 *
 */
@Service
public class PartyServicesImpl extends BaseServices implements PartyServices {
	
	private Logger logger = Logger.getLogger(PartyServicesImpl.class);
	
	@Autowired
	private PartyMapper		partyMapper;
	
	@Autowired
	private UserLoginMapper	userLoginMapper;
	
	@Autowired
	private PersonMapper	personMapper;
	
	@Autowired
	private PartyRoleMapper	partyRoleMapper;
	
	
	@Override
	public Party loadByPrimaryKey(Long partyId) {

		if (partyId == null) {
			throw new ParametersException("partyId is null");
		}

		Party party = partyMapper.selectByPrimaryKey(partyId);
		return party;

	}
	
	@Override
	public void modifyByPrimaryKey(Party party) {
		
		
		bossTransactionTemplate.execute(new TransactionCallbackWithoutResult() {
			
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				if (party == null) {
					throw new ParametersException("party is null!");
				}
				
				if(party.getPartyId() == null) {
					throw new ParametersException("PartyId is null!");
				}
				
				partyMapper.updateByPrimaryKey(party);
				// 修改登录用户信息
				userLoginMapper.updateByPrimaryKey(party.getUserLogin());
				// 修改person信息
				personMapper.updateByPrimaryKey(party.getPerson());

				// 删除当前当事人对应的角色
				partyRoleMapper.deleteByPartyId(party.getPartyId());
				PartyRole partyRole = new PartyRole();
				partyRole.setRoleId(party.getRoleId());
				partyRole.setPartyId(party.getPartyId());
				partyRoleMapper.insert(partyRole);
				
			}
		});

	}
	
	@Override
	public PageModel<Party> loadToPage(PartyQuery partyQuery) {

		List<Party> datas = partyMapper.selectForPage(partyQuery);
		Integer total = partyMapper.countForPage(partyQuery);
		PageModel<Party> pm = new PageModel<Party>(total, datas);
		return pm;
	}
	
	/**
	 * 判断字段是否唯一
	 * @param verifykey
	 * @param excludeKey
	 * @param type
	 * @return
	 */
	private boolean isExist(String verifykey, String excludeKey, String type) {
		boolean b = false;
		switch (type) {
			case "username":
				
				UserLogin userLogin = userLoginMapper.selectByUserLoginId(verifykey);
				if (userLogin == null) {
					b = false;
				} else {
					
					b = true;
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(userLogin.getUserLoginId())) {
							b = false;
						}
					}
				}
				break;
			
			case "mobile":
				Person mPerson = personMapper.selectByMobile(verifykey);
				if (mPerson == null) {
					b = false;
				} else {
					
					b = true;
					
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(mPerson.getMobile())) {
							b = false;
						}
					}
				}
				break;
			
			case "email":
				
				Person ePerson = personMapper.selectByEmail(verifykey);
				if (ePerson == null) {
					b = false;
				} else {
					b = true;
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(ePerson.getEmail())) {
							b = false;
						}
					}
				}
				
				break;
			default:
				
				break;
		}
		
		return b;
	}
	
	@Override
	public Boolean checkExist(String verifykey, String excludeKey, String type) {

		if (StringUtils.isBlank(verifykey)) {
			throw new ParametersException("校验值为空");
		}

		if (StringUtils.isBlank(type)) {
			throw new ParametersException("校验值为空");
		}

		boolean b = isExist(verifykey, excludeKey, type);

		return b;
	}
	
	@Override
	public Party create(final Party party) {

		return bossTransactionTemplate.execute(new TransactionCallback<Party>() {

			@Override
			public Party doInTransaction(TransactionStatus status) {
				
				try {
					
					// 验证当事人字段
					String partyType = party.getPartyType();
					if (StringUtils.isBlank(partyType)) {
						throw new ParametersException("partyType is blank");
					}

					String partyStatus = party.getPartyStatus();
					if (StringUtils.isBlank(partyStatus)) {
						throw new ParametersException("partyStatus is blank");
					}

					// 验证用户名
					UserLogin userLogin = party.getUserLogin();
					Person person = party.getPerson();
					String userLoginId = userLogin.getUserLoginId();
					if (StringUtils.isBlank(userLoginId)) {
						throw new ParametersException("userLoginId is blank");
					}

					boolean b = isExist(userLoginId, null, "username");
					if (b) {
						throw new ParametersException("登陆账户已存在");

					}
					// 验证密码字段
					String password = userLogin.getCurrentPassword();
					if (StringUtils.isBlank(password)) {
						throw new ParametersException("password is blank");
					}

					String email = person.getEmail();
					if (StringUtils.isNotBlank(email) && isExist(email, null, "email")) {
						throw new ParametersException("邮箱账户已存在");
					}

					String mobile = person.getMobile();
					if (StringUtils.isNotBlank(mobile) && isExist(mobile, null, "mobile")) {
						throw new ParametersException("手机号码已存在");
					}

					// 创建party
					party.setUserLoginId(userLogin.getUserLoginId());
					party.setCreatedTime(new Date());
					partyMapper.insertBackPrimaryKey(party);

					// 创建登录帐户

					userLogin.setCurrentPassword(MD5Util.Md5(userLogin.getCurrentPassword()));
					userLogin.setPartyId(party.getPartyId());
					userLogin.setRegisterTime(new Date());
					userLogin.setRegisterIp(IPUtil.getRemoteAddr(WebContext.getRequest()));
					userLoginMapper.insert(userLogin);

					// 创建人员信息
					person.setUserLoginId(userLogin.getUserLoginId());
					person.setPartyId(party.getPartyId());
					personMapper.insert(person);

					// 创建当事人角色信息
					PartyRole partyRole = new PartyRole();
					partyRole.setRoleId(party.getRoleId());
					partyRole.setPartyId(party.getPartyId());
					partyRoleMapper.insert(partyRole);

					return party;
					
				}catch (ParametersException e) {
					logger.error(e);
					status.setRollbackOnly();
					throw e;
				}catch (Exception e) {
					logger.error(e);
					status.setRollbackOnly();
					throw e;
				}

				

			}
		});
	}
	
	@Override
	public void deleteByPrimaryKey(Long partyId) {

		if (partyId == null) {
			throw new ParametersException("partyId is null!");
		}
		partyMapper.deleteByPrimaryKey(partyId);

		// 删除当事人角色信息
		partyRoleMapper.deleteByPartyId(partyId);

	}

	
	
	@Override
	public void changeStatus(Long partyId, String status) {

		if (partyId == null) {
			throw new ParametersException("partyId is null!");
		}
		Party party = new Party();
		party.setPartyId(partyId);
		if (status.equals("freeze")) {
			party.setPartyStatus(PartyStatusEnum.FREEZE.toString());
		} else {
			party.setPartyStatus(PartyStatusEnum.NORMAL.toString());
		}
		partyMapper.updateByPrimaryKey(party);

	}
	

	
}
